function [heartRate_ATPD,slope] = FUN_adaptiveTPD(data)
%ATPD Adaptive Threshold Peak Detection Algorithm
%   Time : 2016-07-01 13:32:43
%   Version:V0.1
%   Author:@hiyangdong

%% Data preparation and preproccess
% sample time and frequency
% generate time and frequency sequence
size = length(data);
sampletime = 0.01;                                  %sample time that unit is second
ts = sampletime;
t = 0:sampletime:(size-1) * sampletime;             %time point
samplefreq = 1/sampletime;                          %sample frequency that unit is Hz
fs = samplefreq;
f = (0:(size-1))/size*samplefreq;                   %frequency point
FontSize = 12;   %12~16

%% plot data and peaks
[pks,locs,w,p] = findpeaks(data, 'MinPeakDistance',0.1*fs);
% [pks,locs,w,p] = findpeaks(data, 'MinPeakDistance',25);

%% adaptive threshold
slope = zeros(1,size);
timeThreshold = 2 * fs;
factor = 0.5;
grad = 0;
num = 1;
peak = pks(num);
loca = locs(num);
count = 0;

for i = 1 : size
    if i < locs(1)
        slope(i) = data(i);
        
    elseif i == locs(num)
        slope(i) = peak - grad * (i - loca);
        if slope(i) <= pks(num)
            count = count+1;
            slope(i) = pks(num);
            [mini,index] = min(data(loca:locs(num)));
            if num == 1
                mini = data(1);
                index = locs(1);
            end
            grad = factor * (peak-mini) / index;
            peak = pks(num);
            loca = locs(num);
            peakGood(count) = loca;
        else
            if locs(num) - loca > timeThreshold
                count = count+1;
                slope(i) = pks(num);
                [mini,index] = min(data(loca+1:locs(num)));
                if num == 1
                    mini = data(1);
                    index = 1;
                end
                grad = factor * (peak-mini) / index;
                peak = pks(num);
                loca = locs(num);
                peakGood(count) = loca;
            end
        end
        if num == 1
            start = locs(num);
        end
        if num == length(locs)
            finish = locs(num);
        end
        if num < length(locs)
            
            num = num + 1;
        end
    else
        slope(i) = peak - grad * (i - loca);
    end
end

%% calculate heart rate (bpm)
heartRate_ATPD = (count-1)/(finish-start)*fs*60
end
